package com.zsgeek.wisdchain.qutu.view.home;

import android.Manifest;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.company.keystore.wallet.WalletUtility;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.zsgeek.wisdchain.qutu.BaseActivity;
import com.zsgeek.wisdchain.qutu.R;
import com.zsgeek.wisdchain.qutu.base.SQL.QuTuDBHelper;
import com.zsgeek.wisdchain.qutu.base.SQL.QuTuDao;
import com.zsgeek.wisdchain.qutu.base.customControl.ClearEditText;
import com.zsgeek.wisdchain.qutu.base.event.PreferenceHelper;
import com.zsgeek.wisdchain.qutu.base.http.JsonRequest;
import com.zsgeek.wisdchain.qutu.base.http.JsonRequestCallBack;
import com.zsgeek.wisdchain.qutu.base.model.BaseModel;
import com.zsgeek.wisdchain.qutu.base.model.WdcAllWalletTable;
import com.zsgeek.wisdchain.qutu.popup.dialog.DialogUtil;
import com.zsgeek.wisdchain.qutu.tools.LogUtil;
import com.zsgeek.wisdchain.qutu.tools.TextUtils;
import com.zsgeek.wisdchain.qutu.tools.ToastHelper;
import com.zsgeek.wisdchain.qutu.tools.UrlPathHelper;
import com.zsgeek.wisdchain.qutu.view.MainActivity;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * 导入钱包
 */
public class ImportWalletActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks {

    @BindView(R.id.import_keystore_et)
    ClearEditText importKeystoreEt;
    @BindView(R.id.import_password_et)
    ClearEditText importPasswordEt;
    @BindView(R.id.import_recommendation_code_et)
    ClearEditText importRecommendationCodeEt;
    @BindView(R.id.login_btn)
    TextView loginBtn;

    private QuTuDao quTuDao;
    private String tableName;
    private List<WdcAllWalletTable> quTuAllWalletTableList;

    private final int RC_CAMERA_PERM = 0x101;
    private final String[] WRITE_EXTERNAL_AND_CAMERA =
            {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};

    @Override
    public int getLayoutId() {
        return R.layout.activity_import_wallet;
    }

    @Override
    protected void initView() {
        setTitle(R.string.import_wallet);
        setToolbarRight(null, R.mipmap.qr_code_small_black_bg, 19, 19, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkCameraPermission();
            }
        });
    }

    @Override
    protected void initDate(Bundle savedInstanceState) {
        try {
            tableName = QuTuDBHelper.TABLE_NAME_MarketSearchTable;
            if (quTuDao == null)
                quTuDao = new QuTuDao(this, tableName);
            new GetAllDate().execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnClick({R.id.login_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.login_btn:
                //String keystore = importKeystoreEt.getText().toString().trim();
                String keystore ="{\"address\":\"1Lemme7nQD8yQ7kFve8FUVFjWAMW5PQtkv\",\"crypto\":{\"cipher\":\"aes-256-ctr\",\"cipherparams\":{\"iv\":\"7dba6ca1b3635cebebc4b80537e4f33b\"},\"ciphertext\":\"1a749559626284e63257c5227c472afa895e81cb2197cf3451131dd955d1849a\"},\"id\":\"af413f0b-7af8-4faf-b53f-6c841b3c7715\",\"kdf\":\"argon2id\",\"kdfparams\":{\"memoryCost\":20480,\"parallelism\":2,\"salt\":\"4dd236bd1159725fb896c6209db5cbb9817cb060e3a4a43cff3ae3fd34f230f4\",\"timeCost\":4},\"mac\":\"3b99989e30000979c6559159225c674071f0d6e15926d2c67a93e449817ebb50\",\"version\":\"1\"}";

                if (TextUtils.isEmpty(keystore)) {
                    ToastHelper.showToast("输入Keystore");
                    return;
                }
                //String password = importPasswordEt.getText().toString();
                String password = "a12345678";
                if (TextUtils.isEmpty(password)) {
                    ToastHelper.showToast("输入密码");
                    return;
                }
                String recommendationCode = importRecommendationCodeEt.getText().toString();
//                if (TextUtils.isEmpty(recommendationCode)) {
//                    ToastHelper.showToast("输入推荐码");
//                    return;
//                }
                try {
                    LogUtil.e("keystore=" + keystore + "; pass=" + password);
                    String publicKey = WalletUtility.keystoreToPubkey(keystore, password);

                    if (TextUtils.isEmpty(publicKey)) {
                        ToastHelper.showToast("keystore内容或者密码错误！");
                    } else {
                        JSONObject jsonObject = JSONObject.parseObject(keystore);
                        String address = jsonObject.getString("address");

                        boolean isNotAddress = false;
                        // 判断本地数据库，地址是否存在，存在则不能导入。
                        if (!TextUtils.isEmpty(quTuAllWalletTableList)) {
                            for (int i = 0; i < quTuAllWalletTableList.size(); i++) {
                                if (quTuAllWalletTableList.get(i).getCoinAddress().equals(address)) {
                                    ToastHelper.showToast("本地已存在，不能再导入");
                                    isNotAddress = true;
                                    break;
                                }
                            }
                        }
                        if (isNotAddress) {
                            startActivity(address);
                        } else {
                            String code = System.currentTimeMillis() + ":";
                            if (!TextUtils.isEmpty(recommendationCode)) {
                                code = code + recommendationCode;
                            }
                            //调用APP接口同步数据
//                            addAdve(address, recommendationCode, "QuTu钱包" + address.substring(0, 4), keystore);
                            addAdve(address, recommendationCode, code, keystore);
                        }
                    }
                } catch (Exception e) {
                    ToastHelper.showToast("keystore内容或者密码错误！");
                    e.printStackTrace();
                }
                break;
        }
    }

    /**
     * 广告发布接口
     */
    private void addAdve(String addr, String userCode, String coinName, String keystore) {
        DialogUtil.createLoadingDialog(this, null);
        new JsonRequest(new JsonRequestCallBack() {
            @Override
            public void showResult(Object object, String taskId) {
                if (object instanceof BaseModel) {
                    BaseModel dataModel = (BaseModel) object;
                    DialogUtil.closeLoadingDialog(ImportWalletActivity.this);
                    if (dataModel.getCode() == 2000) {
//                        ToastHelper.showToast(R.string.success);
                        putWalletDetail(coinName, addr, keystore);
                    } else ToastHelper.showToast(dataModel.getMessage());
                }
            }

            @Override
            public void showError(String errorMsg, String taskId) {
                DialogUtil.closeLoadingDialog(ImportWalletActivity.this);
                ToastHelper.showToast(errorMsg);
            }
        }).postJson(UrlPathHelper.getAdver() + "user/addUser?addr=" + addr + "&userCode=" + userCode
                , true, null, BaseModel.class);
    }

    //提交数据至APP服务器
    private void putWalletDetail(String coinName, String coinAddress, String keystore) {
        //  插入本地数据库
        long insertIdResoult = quTuDao.insertDate(tableName, coinName, coinAddress, keystore);
        if ((int) insertIdResoult != -1) {
//            QuTuApplication.firstInstallation = 1;
            ToastHelper.showToast("导入成功");
//            setResult(-1);
//            startActivity(new Intent(ImportWalletActivity.this, MainActivity.class));
//            finish();
            startActivity(coinAddress);
        } else {
            ToastHelper.showToast("保存失败");
        }
    }

    private void startActivity(String address) {
        PreferenceHelper.getInstance().saveLastUserName(address);
        setResult(-1);
        startActivity(new Intent(ImportWalletActivity.this, MainActivity.class));
        finish();
    }

    private class GetAllDate extends AsyncTask<Void, Void, List<WdcAllWalletTable>> {
        @Override
        protected List<WdcAllWalletTable> doInBackground(Void... voids) {
            return quTuDao.getAllDate(tableName);
        }

        @Override
        protected void onPostExecute(List<WdcAllWalletTable> dataListBeans) {
            if (dataListBeans != null) {
                quTuAllWalletTableList = dataListBeans;
            }
//            super.onPostExecute(dataListBeans);
        }
    }

    @AfterPermissionGranted(RC_CAMERA_PERM)
    public void checkCameraPermission() {
        if (EasyPermissions.hasPermissions(this, WRITE_EXTERNAL_AND_CAMERA)) {
            new IntentIntegrator(this)
                    .setOrientationLocked(false)
                    .setCaptureActivity(ScanQrCodeActivity.class)
                    .initiateScan();
        } else {
            EasyPermissions.requestPermissions(
                    this,
                    getString(R.string.rationale_camera),
                    RC_CAMERA_PERM,
                    WRITE_EXTERNAL_AND_CAMERA);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 0x102 && resultCode == -1) {
            importKeystoreEt.setText(data.getStringExtra("address"));
        } else {
            IntentResult intentResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
            if (intentResult != null) {
                if (intentResult.getContents() == null) {
                    LogUtil.e("onActivityResult: 内容为空");
                } else {
                    importKeystoreEt.setText(intentResult.getContents());
                }
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).build().show();
        }
    }
}
